package org.spiderflow.core.expression.parsing.ast.access;


import org.spiderflow.core.expression.ExpressionError;
import org.spiderflow.core.expression.ExpressionTemplate;
import org.spiderflow.core.expression.ExpressionTemplateContext;
import org.spiderflow.core.expression.parsing.Span;
import org.spiderflow.core.expression.parsing.ast.Expression;

import java.io.IOException;

/**
 * Represents top-level variable access by name. E.g. in the expression "a + 1", <code>a</code> would be encoded as a
 * VariableAccess node. Variables can be both read (in expressions) and written to (in assignments). Variable values are looked
 * up and written to a {@link ExpressionTemplateContext}.
 *
 * @author zhaoshihao
 * @version 2021/11/9 15:44
 **/
public class VariableAccess extends Expression {
    public VariableAccess(Span name) {
        super(name);
    }

    public Span getVariableName() {
        return getSpan();
    }

    @Override
    public Object evaluate(ExpressionTemplate template, ExpressionTemplateContext context) throws IOException {
        Object value = context.get(getSpan().getText());
        if (value == null) {
            throw ExpressionError.error("找不到变量'" + getSpan().getText() + "'或变量值为null", getSpan());
        }
        return value;
    }
}